// src/Mine/Follower.tsx
import React, { useState, useEffect } from 'react';
import { Modal, List, Avatar, Typography, Spin, message } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const { Text } = Typography;

interface FollowRelation {
  followerId: number;
  followeeId: number;
  createdAt: string;
}

interface FollowerUser {
  id: number;
  username: string;
  nickname: string;
  avatar?: string;
  bio?: string;
}

interface FollowerProps {
  visible: boolean;
  onClose: () => void;
  userId: number;
  onFollowChange?: () => void;
}

const Follower: React.FC<FollowerProps> = ({ 
  visible, 
  onClose, 
  userId,
}) => {
  const navigate = useNavigate();
  const [followers, setFollowers] = useState<FollowerUser[]>([]);
  const [loading, setLoading] = useState(false);

  // 改进的用户详情获取
  const fetchUserDetails = async (userId: number): Promise<FollowerUser | null> => {
    try {
      const token = localStorage.getItem('token');
      if (!token) return null;

      // 尝试多个可能的接口
      const endpoints = [
        `/api/users/${userId}`,
        `/api/users/search?uid=${userId}`,
        `/api/user/${userId}/profile`
      ];

      for (const endpoint of endpoints) {
        try {
          const response = await fetch(endpoint, {
            method: 'GET',
            headers: { 
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
          });

          if (response.ok) {
            const userData = await response.json();
            
            // 处理可能的数组返回
            const actualData = Array.isArray(userData) ? userData[0] : userData;
            
            if (actualData) {
              return {
                id: actualData.id || actualData.userId || userId,
                username: actualData.username || actualData.account || `user${userId}`,
                nickname: actualData.nickname || actualData.name || actualData.username || `用户${userId}`,
                avatar: actualData.avatar || actualData.avatarUrl,
                bio: actualData.bio || actualData.description || actualData.signature
              };
            }
          }
        } catch (error) {
          console.warn(`接口 ${endpoint} 失败:`, error);
          continue;
        }
      }

      // 所有接口都失败时返回基础信息
      return {
        id: userId,
        username: `user${userId}`,
        nickname: `用户${userId}`,
        bio: '该用户信息暂不可用'
      };
    } catch (error) {
      console.error('获取用户详情失败:', error);
      return {
        id: userId,
        username: `user${userId}`,
        nickname: `用户${userId}`,
        bio: '网络错误，用户信息获取失败'
      };
    }
  };

  const fetchFollowers = async () => {
    if (!visible) return;
    
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        message.error('请先登录');
        setLoading(false);
        return;
      }

      console.log('开始获取粉丝列表，用户ID:', userId);
      
      // 获取粉丝关系列表
      const response = await fetch(`/api/userfollows/followee/${userId}/followers`, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      console.log('粉丝列表响应状态:', response.status);

      if (response.ok) {
        const followRelations: FollowRelation[] = await response.json();
        console.log('粉丝关系数据:', followRelations);
        
        if (followRelations.length === 0) {
          setFollowers([]);
          return;
        }

        // 提取所有粉丝的ID
        const followerIds = followRelations.map(item => item.followerId);
        console.log('粉丝ID列表:', followerIds);
        
        // 获取每个粉丝的详细信息
        const userDetailsPromises = followerIds.map(id => fetchUserDetails(id));
        const userDetails = await Promise.all(userDetailsPromises);
        
        // 过滤掉获取失败的用户
        const validUsers = userDetails.filter(user => user !== null) as FollowerUser[];
        console.log('有效的粉丝信息:', validUsers);
        
        setFollowers(validUsers);
        
        if (validUsers.length === 0) {
          message.warning('无法获取粉丝的详细信息');
        }
      } else {
        console.error('获取粉丝列表失败，状态码:', response.status);
        message.error('获取粉丝列表失败');
        setFollowers([]);
      }
    } catch (error) {
      console.error('获取粉丝列表失败:', error);
      message.error('网络错误，请检查连接');
      setFollowers([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible && userId) {
      fetchFollowers();
    } else {
      setFollowers([]);
    }
  }, [visible, userId]);

  // 处理头像URL
  const processAvatarUrl = (avatar: string | undefined): string => {
    if (!avatar || avatar === 'null' || avatar === 'undefined' || avatar === '') {
      return '';
    }
    
    if (avatar.startsWith('http')) {
      return avatar;
    }
    
    if (avatar.startsWith('/')) {
      return `http://218.244.141.86:8080${avatar}`;
    } else {
      return `http://218.244.141.86:8080/${avatar}`;
    }
  };

  // 跳转到用户页面
  const handleUserClick = (user: FollowerUser) => {
    if (user && user.id) {
      onClose(); // 先关闭弹窗
      setTimeout(() => {
        navigate(`/user/${user.id}`);
      }, 100);
    } else {
      message.error('用户ID无效');
    }
  };

  return (
    <Modal
      title="我的粉丝"
      open={visible}
      onCancel={onClose}
      footer={null}
      width={450}
      style={{ top: 20 }}
      styles={{
        content: { backgroundColor: '#fdf6e9', borderRadius: '12px' },
        body: { backgroundColor: '#fdf6e9', padding: '20px', borderRadius: '12px', maxHeight: '60vh', overflow: 'auto' },
        header: { backgroundColor: '#fdf6e9', borderBottom: '1px solid #e8d5b5', borderRadius: '12px 12px 0 0' }
      }}
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Spin />
          <div style={{ marginTop: 10, color: '#8b4513' }}>加载粉丝列表...</div>
        </div>
      ) : followers.length > 0 ? (
        <List
          dataSource={followers}
          renderItem={follower => (
            <List.Item 
              style={{ 
                borderBottom: '1px solid #f0f0f0', 
                padding: '12px 0',
                cursor: 'pointer'
              }}
              onClick={() => handleUserClick(follower)}
            >
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '12px', 
                width: '100%',
                transition: 'all 0.3s ease'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'translateX(5px)';
                e.currentTarget.style.backgroundColor = 'rgba(240,224,208,0.3)';
                e.currentTarget.style.borderRadius = '8px';
                e.currentTarget.style.padding = '8px';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'translateX(0)';
                e.currentTarget.style.backgroundColor = 'transparent';
                e.currentTarget.style.padding = '0';
              }}
              >
                <Avatar 
                  size={40} 
                  src={follower.avatar ? processAvatarUrl(follower.avatar) : undefined}
                  icon={<UserOutlined />}
                  style={{ backgroundColor: '#e8d9c7' }}
                  onError={() => {
                    // 头像加载失败时使用默认图标
                    return false;
                  }}
                />
                <div style={{ flex: 1 }}>
                  <Text strong style={{ color: '#8b4513', display: 'block', fontSize: '14px' }}>
                    {follower.nickname}
                  </Text>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    @{follower.username}
                  </Text>
                  {follower.bio && (
                    <Text type="secondary" style={{ fontSize: '11px', display: 'block', marginTop: '2px', lineHeight: '1.2' }}>
                      {follower.bio}
                    </Text>
                  )}
                </div>
              </div>
            </List.Item>
          )}
        />
      ) : (
        <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
          暂无粉丝
        </div>
      )}
    </Modal>
  );
};

export default Follower;